import DataBus from '../databus'
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render'

export default class Board {
  constructor() {
    this.databus = new DataBus()
    
    // 棋盘参数 - 适配竖屏
    this.boardSize = 15 // 15x15
    this.cellSize = Math.min(SCREEN_WIDTH, SCREEN_HEIGHT) / 18 // 自适应格子大小
    this.boardPadding = 20 // 棋盘边距
    this.stoneRadius = this.cellSize * 0.45 // 棋子半径
    
    // 计算棋盘位置 - 居中显示，为控制面板留出空间
    // 只用14个格子的跨度
    this.boardWidth = (this.boardSize - 1) * this.cellSize
    this.boardHeight = (this.boardSize - 1) * this.cellSize
    this.startX = (SCREEN_WIDTH - this.boardWidth) / 2
    // 留出顶部空间给游戏信息，底部空间给控制面板
    this.startY = (SCREEN_HEIGHT - this.boardHeight) / 2 + 40 // 减少顶部空间，为控制面板留出空间
    
    // 确认状态 - 改为二次点击确认
    this.pendingMove = null
    this.previewMove = null // 预览落子
  }

  init() {
    this.databus.initBoard()
    this.pendingMove = null
    this.previewMove = null
  }

  update() {
    // 棋盘更新逻辑
  }

  render(ctx) {
    this.drawBoard(ctx)
    this.drawStones(ctx)
    this.drawPreviewMove(ctx) // 绘制预览落子
    this.drawLastMove(ctx)
  }

  drawBoard(ctx) {
    // 绘制棋盘背景
    ctx.fillStyle = '#DEB887'
    ctx.fillRect(this.startX - 10, this.startY - 10, this.boardWidth + 20, this.boardHeight + 20)
    
    // 绘制棋盘网格
    ctx.strokeStyle = '#8B4513'
    ctx.lineWidth = 2
    // 只绘制15条线（不画最右和最下的线）
    for (let i = 0; i < this.boardSize; i++) {
      // 横线
      ctx.beginPath()
      ctx.moveTo(this.startX, this.startY + i * this.cellSize)
      ctx.lineTo(this.startX + this.boardWidth, this.startY + i * this.cellSize)
      ctx.stroke()
      
      // 竖线
      ctx.beginPath()
      ctx.moveTo(this.startX + i * this.cellSize, this.startY)
      ctx.lineTo(this.startX + i * this.cellSize, this.startY + this.boardHeight)
      ctx.stroke()
    }
    
    // 绘制天元和星位
    const starPoints = [3, 7, 11]
    ctx.fillStyle = '#8B4513'
    for (let i of starPoints) {
      for (let j of starPoints) {
        ctx.beginPath()
        ctx.arc(this.startX + i * this.cellSize, this.startY + j * this.cellSize, 4, 0, 2 * Math.PI)
        ctx.fill()
      }
    }
  }

  drawStones(ctx) {
    for (let i = 0; i < this.boardSize; i++) {
      for (let j = 0; j < this.boardSize; j++) {
        if (this.databus.board[i][j] !== 0) {
          const x = this.startX + j * this.cellSize
          const y = this.startY + i * this.cellSize
          
          // 绘制棋子阴影
          ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
          ctx.beginPath()
          ctx.arc(x + 2, y + 2, this.stoneRadius, 0, 2 * Math.PI)
          ctx.fill()
          
          // 绘制棋子
          if (this.databus.board[i][j] === 1) {
            // 黑棋
            const gradient = ctx.createRadialGradient(x - 5, y - 5, 0, x, y, this.stoneRadius)
            gradient.addColorStop(0, '#666')
            gradient.addColorStop(1, '#000')
            ctx.fillStyle = gradient
          } else {
            // 白棋
            const gradient = ctx.createRadialGradient(x - 5, y - 5, 0, x, y, this.stoneRadius)
            gradient.addColorStop(0, '#fff')
            gradient.addColorStop(1, '#ccc')
            ctx.fillStyle = gradient
          }
          
          ctx.beginPath()
          ctx.arc(x, y, this.stoneRadius, 0, 2 * Math.PI)
          ctx.fill()
          
          // 绘制棋子边框
          ctx.strokeStyle = this.databus.board[i][j] === 1 ? '#000' : '#999'
          ctx.lineWidth = 1
          ctx.stroke()
        }
      }
    }
  }

  drawPreviewMove(ctx) {
    if (this.previewMove) {
      const x = this.startX + this.previewMove.col * this.cellSize
      const y = this.startY + this.previewMove.row * this.cellSize
      
      // 绘制半透明的预览棋子
      ctx.globalAlpha = 0.6
      
      // 绘制棋子阴影
      ctx.fillStyle = 'rgba(0, 0, 0, 0.2)'
      ctx.beginPath()
      ctx.arc(x + 2, y + 2, this.stoneRadius, 0, 2 * Math.PI)
      ctx.fill()
      
      // 绘制预览棋子
      if (this.previewMove.player === 1) {
        // 黑棋预览
        const gradient = ctx.createRadialGradient(x - 5, y - 5, 0, x, y, this.stoneRadius)
        gradient.addColorStop(0, 'rgba(102, 102, 102, 0.8)')
        gradient.addColorStop(1, 'rgba(0, 0, 0, 0.8)')
        ctx.fillStyle = gradient
      } else {
        // 白棋预览
        const gradient = ctx.createRadialGradient(x - 5, y - 5, 0, x, y, this.stoneRadius)
        gradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)')
        gradient.addColorStop(1, 'rgba(204, 204, 204, 0.8)')
        ctx.fillStyle = gradient
      }
      
      ctx.beginPath()
      ctx.arc(x, y, this.stoneRadius, 0, 2 * Math.PI)
      ctx.fill()
      
      // 绘制棋子边框
      ctx.strokeStyle = this.previewMove.player === 1 ? 'rgba(0, 0, 0, 0.8)' : 'rgba(153, 153, 153, 0.8)'
      ctx.lineWidth = 1
      ctx.stroke()
      
      // 绘制闪烁效果
      ctx.globalAlpha = 0.3 + 0.3 * Math.sin(Date.now() * 0.01)
      ctx.strokeStyle = '#FF6B6B'
      ctx.lineWidth = 3
      ctx.beginPath()
      ctx.arc(x, y, this.stoneRadius + 5, 0, 2 * Math.PI)
      ctx.stroke()
      
      // 恢复透明度
      ctx.globalAlpha = 1.0
    }
  }

  drawLastMove(ctx) {
    if (this.databus.lastMove) {
      const x = this.startX + this.databus.lastMove.col * this.cellSize
      const y = this.startY + this.databus.lastMove.row * this.cellSize
      
      // 绘制最后一步的标记
      ctx.strokeStyle = '#FF0000'
      ctx.lineWidth = 3
      ctx.beginPath()
      ctx.arc(x, y, this.stoneRadius + 3, 0, 2 * Math.PI)
      ctx.stroke()
    }
  }

  handleTouch(x, y) {
    // 检查是否点击在棋盘范围内 - 放宽边界检查
    const margin = this.cellSize * 0.3 // 允许一定的点击容差
    if (x < this.startX - margin || x > this.startX + this.boardWidth + margin ||
        y < this.startY - margin || y > this.startY + this.boardHeight + margin) {
      console.log('点击位置超出棋盘范围:', { x, y, startX: this.startX, startY: this.startY, boardWidth: this.boardWidth, boardHeight: this.boardHeight })
      return null
    }
    
    // 计算点击的格子位置 - 修复边界计算
    let col = Math.round((x - this.startX) / this.cellSize)
    let row = Math.round((y - this.startY) / this.cellSize)
    
    // 边界修正 - 确保最右边和最下边可以落子
    if (col >= this.boardSize) col = this.boardSize - 1
    if (row >= this.boardSize) row = this.boardSize - 1
    if (col < 0) col = 0
    if (row < 0) row = 0
    
    console.log('坐标计算:', { 
      x, y, 
      startX: this.startX, startY: this.startY, 
      cellSize: this.cellSize,
      rawCol: Math.round((x - this.startX) / this.cellSize),
      rawRow: Math.round((y - this.startY) / this.cellSize),
      adjustedCol: col,
      adjustedRow: row,
      boardSize: this.boardSize
    })
    
    // 检查位置是否有效 - 确保边界位置可以落子
    if (row < 0 || row >= this.boardSize || col < 0 || col >= this.boardSize) {
      console.log('点击位置超出棋盘范围:', { x, y, row, col, boardSize: this.boardSize })
      return null
    }
    
    // 检查位置是否已经有棋子
    if (this.databus.board[row][col] !== 0) {
      console.log('该位置已有棋子:', { row, col, existingStone: this.databus.board[row][col] })
      return null
    }
    
    console.log('有效点击位置:', { x, y, row, col, player: this.databus.currentPlayer })
    
    // 检查是否是二次点击确认
    if (this.previewMove && this.previewMove.row === row && this.previewMove.col === col) {
      // 二次点击同一位置，确认落子
      this.pendingMove = { ...this.previewMove }
      this.previewMove = null
      console.log('二次点击确认落子:', { row, col, player: this.databus.currentPlayer })
      return {
        needConfirm: true,
        x: col,
        y: row,
        row: row,
        col: col,
        player: this.databus.currentPlayer
      }
    } else {
      // 第一次点击，显示预览
      // 如果之前有预览，先清除
      if (this.previewMove) {
        console.log('清除之前的预览，显示新预览')
        this.previewMove = null
      }
      
      this.previewMove = {
        row: row,
        col: col,
        player: this.databus.currentPlayer
      }
      console.log('显示预览落子:', { row, col, player: this.databus.currentPlayer })
      return null // 不需要确认对话框
    }
  }

  confirmMove() {
    if (!this.pendingMove) {
      console.warn('confirmMove called but no pending move')
      return
    }
    
    const { row, col, player } = this.pendingMove
    
    if (row === undefined || col === undefined || player === undefined) {
      console.error('Invalid pending move:', this.pendingMove)
      this.pendingMove = null
      return
    }
    
    // 落子
    this.databus.board[row][col] = player
    this.databus.lastMove = { row, col }
    this.databus.recordMove(row, col, player)
    
    // 检查是否获胜
    if (this.databus.checkWin(row, col, player)) {
      this.databus.winner = player
      this.databus.gameOver = true
    } else {
      // 检查是否平局
      if (this.databus.checkDraw()) {
        this.databus.winner = 0 // 0表示平局
        this.databus.gameOver = true
      } else {
        // 切换玩家
        this.databus.switchPlayer()
        
        // 在线模式下更新回合状态
        if (this.databus.isOnlineMode) {
          this.databus.isMyTurn = this.databus.currentPlayer === this.databus.myStoneColor
        }
        
        // AI模式下，如果轮到AI，则AI自动落子
        if (this.databus.isAIMode && this.databus.currentPlayer === this.databus.aiPlayer) {
          // 延迟一小段时间，让玩家看到落子效果
          setTimeout(() => {
            this.makeAIMove()
          }, 500)
        }
      }
    }
    
    this.pendingMove = null
  }

  /**
   * AI自动落子
   */
  makeAIMove() {
    if (this.databus.gameOver) return
    
    // 获取AI实例（兼容不同环境）
    let gameAI = null
    if (typeof window !== 'undefined' && window.gameAI) {
      gameAI = window.gameAI
    } else if (typeof GameGlobal !== 'undefined' && GameGlobal.gameAI) {
      gameAI = GameGlobal.gameAI
    }
    
    if (!gameAI) {
      console.error('AI实例未找到')
      return
    }
    
    // 记录AI开始思考时间
    const startTime = Date.now()
    
    // 获取AI的下一步落子位置
    const aiMove = gameAI.getNextMove(this.databus.board, this.databus.currentPlayer)
    
    // 记录AI思考结束时间
    const endTime = Date.now()
    
    if (aiMove) {
      // 直接落子，不需要确认
      this.databus.board[aiMove.row][aiMove.col] = this.databus.currentPlayer
      this.databus.lastMove = { row: aiMove.row, col: aiMove.col }
      this.databus.recordMove(aiMove.row, aiMove.col, this.databus.currentPlayer)
      
      // 检查是否获胜
      if (this.databus.checkWin(aiMove.row, aiMove.col, this.databus.currentPlayer)) {
        this.databus.winner = this.databus.currentPlayer
        this.databus.gameOver = true
      } else {
        // 检查是否平局
        if (this.databus.checkDraw()) {
          this.databus.winner = 0 // 0表示平局
          this.databus.gameOver = true
        } else {
          // 切换回玩家
          this.databus.switchPlayer()
        }
      }
    }
  }

  setPendingMove(move) {
    if (move && move.row !== undefined && move.col !== undefined && move.player !== undefined) {
      this.pendingMove = move
    } else {
      console.error('Invalid move data:', move)
      this.pendingMove = null
    }
  }

  clearPreview() {
    this.previewMove = null
    this.pendingMove = null
  }
} 